<template>
  <div class="app-container">
    <!--    <el-alert-->
    <!--      v-show="!loading"-->
    <!--      :title="$t('OFFLINE')"-->
    <!--      type="error"-->
    <!--    />-->
    <el-row :gutter="5">
      <el-col v-for="(item,index) in myDeviceCoreList" :key="index" :span="6">
        <el-input :value="item">
          <template slot="prepend">
            <el-button
              icon="el-icon-setting"
              type="primary"
              @click="deviceSetting(item)"
            />
          </template>
          <template slot="prepend">
            <el-button
              icon="el-icon-message"
              type="primary"
              @click="openSend(item)"
            />
          </template>
          <template slot="append">
            <el-button type="danger" @click="removeDeviceCore(item)">{{ $t('delete') }}</el-button>
          </template>
        </el-input>
      </el-col>
      <el-col :span="6">
        <el-input v-model="deviceCore" :placeholder="$t('deviceCore')">
          <template slot="append">
            <el-button type="primary" @click="addDeviceCore">{{ $t('add') }}</el-button>
          </template>
        </el-input>
      </el-col>
    </el-row>
    <el-form inline class="mt-2" @submit.native.prevent>
      <!--      <el-form-item :label="$t('deviceCore')">-->
      <!--        <el-input v-model="deviceCore" :placeholder="$t('deviceCore')" />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item>-->
      <!--        <el-button type="primary" @click="addDeviceCore">{{ $t('add') }}</el-button>-->
      <!--      </el-form-item>-->
      <el-form-item :label="$t('type')">
        <el-select v-model="type" @change="typeChange">
          <el-option :label="$t('all')" value=""/>
          <el-option :label="$t('warn')" value="deviceWarn"/>
          <el-option :label="$t('upload')" value="deviceUpload"/>
          <el-option :label="$t('status')" value="deviceStatus"/>
          <el-option :label="$t('send')" value="serverSend"/>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('limit')">
        <el-input v-model="limitNumber"/>
      </el-form-item>
      <el-form-item>
        <!--        <el-button type="primary" disabled>{{ loadingText }}</el-button>-->
        <el-button type="primary" @click="cleanClick">{{ $t('clean') }}</el-button>
      </el-form-item>
      <el-form-item>
        <el-button
          icon="el-icon-news"
          type="primary"
          @click="openNew"
        />
      </el-form-item>
    </el-form>

    <div
      class="uni-scroll"
      style="height: calc(100vh - 180px)"
    >
      <div
        v-for="(item ,index) in list"
        v-if="type === '' || type === item.type"
        :key="index"
        style="padding: 5px"
      >
        <el-alert
          :title="item.deviceCore + '[ '+item.time+' ]'"
          type="info"
          :close-text="$t(item.type)"
        />
        <el-input v-model="item.raw" type="textarea" :rows="3"/>
      </div>
    </div>

    <el-dialog
      :visible.sync="showSetting"
      width="1200px"
      top="15px"
    >
      <device-setting
        :device-core="deviceCore"
        class="uni-scroll"
        style="height: 600px"
      />
    </el-dialog>

    <el-dialog
      :visible.sync="showSend"
      top="15px"
    >
      <el-input
        v-model="sendText"
        type="textarea"
        :rows="20"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="showSend = false">{{ $t('cancel') }}</el-button>
        <el-button type="primary" @click="sendToDevice">{{ $t('send') }}</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { failureNotice, formatDate, successNotice } from '@/util/common'
import DeviceSetting from '@/components/DeviceSetting'
import { detailsDevice, sendToDevice } from '@/api/iot/iotDeviceApi'
import { leaveWebSocket, listenWebSocket } from '@/util/websocketTool'

export default {
  name: 'IotNow',
  components: {
    DeviceSetting
  },
  data() {
    return {
      list: [],
      // loading: false,
      // loadingText: null,
      deviceCore: null,
      myDeviceCoreList: [],
      // ws: null,
      type: '',
      showSetting: false,
      showSend: false,
      sendText: null,
      limitNumber: 60,
      wsMonitorList: []
    }
  },
  beforeDestroy() {
    this.closeSocket()
  },
  mounted() {
    // this.loading = true
    // this.loadingText = this.$t('open')
    const param = this.$route.query
    if (param.deviceCore) {
      this.deviceCore = param.deviceCore
      this.addDeviceCore()
    }
    // this.initSocket()
  },
  methods: {
    sendToDevice() {
      sendToDevice({
        deviceCore: this.deviceCore,
        msg: this.sendText
      }).then(res => {
        const { data } = res
        if (data) {
          successNotice(this)
        }
      })
    },
    openSend(deviceCore) {
      this.deviceCore = deviceCore
      this.showSend = true
    },
    closeSocket() {
      // if (this.ws == null) {
      //   return
      // }
      // this.myDeviceCoreList.forEach(deviceCore => {
      //   this.ws.send(JSON.stringify({
      //     cmd: 'unBindRoom',
      //     param: 'iot:monitor:' + deviceCore
      //   }))
      // })
      // this.ws.onclose = null
      // this.ws.close()
      // this.ws = null
      this.wsMonitorList.forEach(item => {
        leaveWebSocket(item)
      })
    },
    removeDeviceCore(deviceCore) {
      for (const i in this.myDeviceCoreList) {
        if (this.myDeviceCoreList[i] === deviceCore) {
          // this.ws.send(JSON.stringify({
          //   cmd: 'unBindRoom',
          //   param: 'iot:monitor:' + deviceCore
          // }))
          this.wsMonitorList.forEach(item => {
            if (item.room === ('iot:monitor:' + deviceCore)) {
              leaveWebSocket(item)
            }
          })
          this.myDeviceCoreList.splice(i, 1)
          break
        }
      }
      this.init()
    },
    addDeviceCore() {
      if (!this.deviceCore || this.deviceCore === '') {
        failureNotice(this, this.$t('deviceCore'))
        return
      }
      if (this.myDeviceCoreList.includes(this.deviceCore)) {
        failureNotice(this, this.$t('deviceCore'))
        return
      }
      detailsDevice({
        deviceCore: this.deviceCore
      }).then(res => {
        const { code } = res
        if (code === '200') {
          // this.ws.send(JSON.stringify({
          //   cmd: 'bindRoom',
          //   param: 'iot:monitor:' + this.deviceCore
          // }))
          const wsMonitor = {
            room: 'iot:monitor:' + this.deviceCore,
            onmessage: this.onSocketMsg
          }
          listenWebSocket(wsMonitor)
          this.wsMonitorList.push(wsMonitor)
          this.myDeviceCoreList.unshift(this.deviceCore)
          this.deviceCore = ''
        }
      })
    },
    onSocketMsg(msg) {
      // if (!this.loading) {
      //   return
      // }
      const time = formatDate(this, msg.timestamp)
      const data = JSON.parse(msg.msg)
      if (this.list.length > this.limitNumber) {
        this.list.splice(this.limitNumber, (this.list.length - this.limitNumber))
      }
      this.list.unshift({
        deviceCore: msg.extend.deviceCore,
        raw: data.raw,
        type: data.type,
        time: time
      })

    },
    // initSocket() {
    //   const that = this
    //   this.closeSocket()
    //   this.ws = newWebSocket()
    //   this.ws.onopen = () => {
    //     that.loading = true
    //     that.loadingText = that.$t('close')
    //     this.myDeviceCoreList.forEach(deviceCore => {
    //       that.ws.send(JSON.stringify({
    //         cmd: 'bindRoom',
    //         param: 'iot:monitor:' + deviceCore
    //       }))
    //     })
    //   }
    //   this.ws.onerror = function(e) {
    //     console.log('WebSocket is error' + e.code + ' ' + e.reason + ' ' + e.wasClean)
    //     that.loading = false
    //     that.loadingText = this.$t('open')
    //     that.ws.close()
    //     setTimeout(function() {
    //       that.initSocket()
    //     }, 2000)
    //   }
    //   this.ws.onclose = function(e) {
    //     console.log('WebSocket is close' + e.code + ' ' + e.reason + ' ' + e.wasClean)
    //     that.loading = false
    //     that.loadingText = this.$t('open')
    //     setTimeout(function() {
    //       that.initSocket()
    //     }, 2000)
    //   }
    //   this.ws.onmessage = function(msg) {
    //     if (!that.loading) {
    //       return
    //     }
    //     msg = JSON.parse(msg.data)
    //     const time = formatDate(that, msg.timestamp)
    //     const data = JSON.parse(msg.msg)
    //     if (that.list.length > that.limitNumber) {
    //       that.list.splice(that.limitNumber, (that.list.length - that.limitNumber))
    //     }
    //     that.list.unshift({
    //       deviceCore: msg.extend.deviceCore,
    //       raw: data.raw,
    //       type: data.type,
    //       time: time
    //     })
    //   }
    // },
    cleanClick() {
      this.list = []
    },
    openNew() {
      window.open('#/iot/now2/')
    },
    typeChange(type) {
      this.type = type
    },
    deviceSetting(deviceCore) {
      this.deviceCore = deviceCore
      this.showSetting = true
    }
  }
}
</script>
<style scoped>

</style>
